package huichun_m

import (
	"frozen-go-mini/common/domain"
	"frozen-go-mini/common/resource/mysql"
	"gorm.io/gorm/clause"
)

// UserCollect  用户收藏
type UserCollect struct {
	mysql.Entity
	UserId    mysql.ID `gorm:"column:user_id"`    //  用户id
	ProductId mysql.ID `gorm:"column:product_id"` //  商品id
	Collect   bool     `gorm:"column:collect"`    //  收藏 1:收藏 0:取消收藏
}

func (UserCollect) TableName() string {
	return "user_collect"
}

// 增加用户收藏
func AddUserCollect(model *domain.Model, collect UserCollect) error {
	if err := model.DB().Model(UserCollect{}).Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "user_id"}, {Name: "product_id"}},
		DoUpdates: clause.Assignments(map[string]interface{}{
			"collect": collect.Collect,
		}),
	}).Create(&collect).Error; err != nil {
		model.Log.Errorf("AddUserCollect fail:%v", err)
		return err
	}
	return nil
}

// 获取我的收藏
func GetMyCollect(model *domain.Model, userId mysql.ID) []HuichunProduct {
	var res []HuichunProduct
	if err := model.DB().Table(HuichunProduct{}.TableName()+" p").
		Joins("INNER JOIN "+UserCollect{}.TableName()+" u").
		Select("p.*").
		Where("u.product_id = p.id").Where("p.status = 1").Where("u.collect = 1").
		Where("u.user_id = ?", userId).
		Order("u.updated_time DESC").Find(&res).Error; err != nil {
		model.Log.Errorf("GetMyFootprint fail:%v", err)
	}
	return res
}

// 获取是否我收藏的
// return productId->isCollect
func GetIsMyCollect(model *domain.Model, userId mysql.ID) map[mysql.ID]bool {
	res := make(map[mysql.ID]bool)
	var rows []UserCollect
	if err := model.DB().Model(UserCollect{}).Where("user_id = ? AND collect = 1", userId).Find(&rows).Error; err != nil {
		model.Log.Errorf("GetIsMyCollect fail:%v", err)
	}
	for _, v := range rows {
		res[v.ProductId] = true
	}
	return res
}
